//
//  ResponseHandler.swift
//  Solo
//
//  Created by JunMing on 2022/8/30.
//  
//

import Foundation
import Alamofire

public class ResponseHandler: ResponseSerializer {
    public let dataPreprocessor: DataPreprocessor
    public let emptyResponseCodes: Set<Int>
    public let emptyRequestMethods: Set<HTTPMethod>
    public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
                emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
                emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods) {
        self.dataPreprocessor = dataPreprocessor
        self.emptyResponseCodes = emptyResponseCodes
        self.emptyRequestMethods = emptyRequestMethods
    }
    
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
        if let error = error {
            switch error.asAFError {
            case .responseValidationFailed(reason: _):
                throw AFError.responseSerializationFailed(reason: .customSerializationFailed(error: error))
            default:
                throw error
            }
        }
        
        guard var data = data, !data.isEmpty else {
            guard emptyResponseAllowed(forRequest: request, response: response) else {
                throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
            }
            return Data()
        }
        
        data = try dataPreprocessor.preprocess(data)
        return data
   }
}
